<template>
  <div class="app-container">
    <!--搜索栏-->
    <div class="filter-container">
      <el-input
        v-model="listQuery.search"
        placeholder="全局搜索"
        style="width:200px;"
        class="filter-item"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handlerFilter"
      >搜索</el-button>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        style="margin-left:10px;"
        @click="handlerCreate"
      >添加</el-button>
    </div>
    <!--表格-->
    <el-table
      v-loading="loadingTableVisible"
      :element-loading-text="loadingTableTitle"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :data="list"
      border
      fit
      highlight-current-row
      style="width:100%;font-size:12px;"
      :row-style="{height:'30px'}"
      :cell-style="{padding:'3px'}"
    >
      <el-table-column label="编号" prop="id" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否发布" prop="isRelease" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRelease"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handlerRelease(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="creationTime" align="center" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="success" size="mini" round @click="handlerAuth(row)">授权</el-button>
          <el-button type="primary" size="mini" round @click="handlerUpdate(row)">编辑</el-button>
          <el-button type="danger" size="mini" round @click="handlerDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--创建与编辑-->
    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
        class="form-inline"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" />
        </el-form-item>
        <!-- <el-form-item v-for="(introduction,index) in temp.Introductions" label="介绍">
          <el-input v-model="introduction"></el-input>
        </el-form-item> -->
        <el-form-item v-for="(item,index) in temp.details" label="详情">
          <el-select v-model="item.month" placeholder="月份" style="width:80px;">
            <el-option v-for="m in moeths" :key="m" :label="m" :value="m" />
          </el-select>
          <el-input v-model="item.price" placeholder="价格" style="width:80px;" />
          <el-input v-model="item.discount" placeholder="折扣" style="width:80px;" />
          <el-button @click.prevent="removeDomain(item)">删除</el-button>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogFormVisible=false">取消</el-button>
        <el-button @click="addDomain">新增详情</el-button>
        <el-button type="primary" @click="saveData">保存</el-button>
      </div>
    </el-dialog>
    <!--授权-->
    <el-dialog :visible.sync="dialogAuthVisible" :title="dialogAuthTitle">
      <el-tree
        ref="tree"
        :data="data"
        show-checkbox
        node-key="name"
        highlight-current
        :props="defaultProps"
      />
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogAuthVisible=false">取消</el-button>
        <el-button type="primary" @click="SaveTreeData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import waves from "@/directive/waves"; // 波纹按钮
import { parseTime } from "@/utils";
import {
  getProjectList,
  getProjectInfo,
  saveProjectInfo,
  deleteProjectInfo,
  release,
  getProjectPermission,
  authoriza
} from "@/api/site/project";
import { getPermission } from "@/api/account";
export default {
  directives: { waves },
  data() {
    return {
      listQuery: {
        search: ""
      },
      defaultProps: {
        children: "children",
        label: "displayName"
      },
      list: [],
      data: [],
      total: 0,
      loadingTableTitle: "拼命加载中",
      loadingTableVisible: true,
      dialogFormTitle: "",
      dialogFormVisible: false,
      dialogAuthVisible: false,
      dialogAuthTitle: "",
      temp: {
        id: undefined,
        name: "",
        description: "",
        details: [
          {
            id: undefined,
            month: undefined,
            price: undefined,
            discount: undefined
          }
        ]
      },
      rules: {},
      moeths: [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 18, 24]
    };
  },
  created() {
    this.getProjects();
  },
  methods: {
    getProjects() {
      getProjectList(this.listQuery)
        .then(response => {
          this.loadingTableVisible = false;
          this.list = response.data.items;
          this.total = response.data.total;
        })
        .catch(() => {
          this.loadingTableTitle = "拼命加载中";
          this.loadingTableVisible = false;
        });
    },
    // 重置数据模型
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        description: "",
        details: [
          {
            id: undefined,
            month: undefined,
            price: undefined,
            discount: undefined
          }
        ]
      };
    },
    // 搜索事件
    handlerFilter() {
      this.loadingTableTitle = "正在搜索";
      this.loadingTableVisible = true;
      this.getProjects();
    },
    // 创建事件
    handlerCreate() {
      this.resetTemp();
      this.dialogFormTitle = "添加产品信息";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 编辑事件
    handlerUpdate(row) {
      this.dialogFormTitle = "编辑产品信息";
      this.dialogFormVisible = true;
      getProjectInfo(row.id).then(response => {
        this.temp = response.data;
        if (response.data.details.length == 0) {
          this.temp.details.push({
            id: undefined,
            month: undefined,
            price: undefined,
            discount: undefined
          });
        }
      });
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 删除事件
    handlerDelete(row) {
      this.$confirm("确定删除产品信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const loading = this.$loading({ text: "正在删除数据" });
        deleteProjectInfo(row.id)
          .then(response => {
            loading.close();
            this.$notify({
              title: "Success",
              message: response.data,
              type: "success",
              duration: 1000
            });
            this.getProjects();
          })
          .catch(() => {
            loading.close();
          });
      });
    },
    // 发布产品事件
    handlerRelease(row) {
      const loading = this.$loading({ text: "正在发布产品" });
      release(row.id)
        .then(response => {
          loading.close();
          this.$message({
            message: response.message,
            type: response.success ? "success" : "error"
          });
          this.getProjects();
        })
        .catch(() => {
          loading.close();
        });
    },
    // 授权事件
    handlerAuth(row) {
      this.dialogAuthVisible = true;
      this.dialogAuthTitle = "授权" + row.name;
      this.temp.id = row.id;
      getPermission().then(response => {
        this.data = response.data.permissions;
      });
      getProjectPermission(row.id).then(response => {
        this.$refs.tree.setCheckedKeys(response.data);
      });
    },
    // 保存数据
    saveData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const loading = this.$loading({ text: "正在保存数据" });
          saveProjectInfo(this.temp)
            .then(response => {
              loading.close();
              this.dialogFormVisible = false;
              this.$notify({
                title: "Success",
                message: response.data,
                type: "success",
                duration: 1000
              });
              this.getProjects();
            })
            .catch(error => {
              loading.close();
              console.info(error);
            });
        }
      });
    },
    SaveTreeData() {
      const loading = this.$loading({ text: "正在授权" });
      var data = {
        id: this.temp.id,
        values: this.$refs.tree.getCheckedKeys()
      };
      authoriza(data)
        .then(response => {
          loading.close();
          this.dialogAuthVisible = false;
          this.$notify({
            title: "Success",
            message: response.message,
            type: "success",
            duration: 2000
          });
        })
        .catch(() => {
          loading.close();
        });
    },
    // 移除详情列表
    removeDomain(item) {
      var index = this.temp.details.indexOf(item);
      if (index !== -1) {
        this.temp.details.splice(index, 1);
      }
    },
    // 添加详情列表
    addDomain() {
      this.temp.details.push({
        id: undefined,
        moeth: undefined,
        price: undefined,
        discount: undefined
      });
    }
  }
};
</script>
